package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        //1. 获取本次请求的URI
        String requestURI = req.getRequestURI();

        //2. 判断本次请求是否需要处理
        String[] uris = new String[]{
                //放行管理端资源
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/common/**",
                "/employee/logout",

                //放行移动端资源
                "/user/login",
                "/ping",
                "/pay/fallback",
                "/user/sendMsg"
        };

        //3. 如果不需要处理,则直接放行
        boolean match = match(requestURI, uris);
        if (match){
            chain.doFilter(req, resp);
            return;
        }

        //4.1 判断管理端员工登录状态,如果已登录,则直接放行
        if(req.getSession().getAttribute("employee")!= null){
            //将当前登录用户的id存入ThreadLocal
            BaseContext.setCurrentId((Long) req.getSession().getAttribute("employee"));
            chain.doFilter(req, resp);
            return;
        }

        //4.2 判断移动端员工登录状态,如果已登录,则直接放行
        if(req.getSession().getAttribute("user")!= null){
            //将当前登录用户的id存入ThreadLocal
            BaseContext.setCurrentId((Long) req.getSession().getAttribute("user"));
            chain.doFilter(req, resp);
            return;
        }

        log.info("拦截到请求:{}", req.getRequestURI());
        //5. 如果未登录则返回未登录结果
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }


    private static boolean match(String uri,String[] uris){
        for (String s : uris) {
            if (PATH_MATCHER.match(s,uri)){
                return true;
            }
        }

        return false;
    }
}
